package com.qf.efserver.sleep.service.Impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.common.core.entity.SleepRecords;
import com.qf.common.core.entity.SleepTime;
import com.qf.common.core.utils.UserUtils;
import com.qf.efserver.sleep.mapper.Sleepmapper;
import com.qf.efserver.sleep.param.SleepParam;
import com.qf.efserver.sleep.service.SleepService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SleepServiceImpl implements SleepService {

   @Resource
   private Sleepmapper sleepmapper;


    @Override
    public void addSleep(SleepParam param) {
        SleepRecords sleepRecords = new SleepRecords();
        sleepRecords.setSleepEnd(param.getEndTime());
        sleepRecords.setUserId(UserUtils.getUid());
         sleepmapper.insert(sleepRecords);
    }

    @Override
    public SleepTime selectSleepByUserId() {
        long[]  time={0};
        Integer uid = UserUtils.getUid();
        List<SleepRecords> sleepRecordsList = sleepmapper.selectList(new QueryWrapper<SleepRecords>().eq("user_id", uid));

        SleepTime sleepTime = new SleepTime();
        sleepTime.setUserId(uid);
        sleepRecordsList.forEach(item -> {


            long hours = DateUtil.between(item.getSleepStart(), item.getSleepEnd(), DateUnit.HOUR);
            time[0] += hours;
        });
        int hour =(int) time[0];
sleepTime.setSleepTime(hour);

        if (hour>=8){
           sleepTime.setSleepQuality(1);
        }else if ( hour>=6 && hour<8) {
            sleepTime.setSleepQuality(2);
        }else if (hour>=4 && hour<6){
            sleepTime.setSleepQuality(3);
        }else if (hour>0 && hour<4){
            sleepTime.setSleepQuality(4);
        }
        return sleepTime;
    }
}
